const app = getApp();
var urls = [],
  imagesLength = 0
Page({

  /**
   * 页面的初始数据
   */
  data: {
    activeTab: 'image',
    showMenu:true,
    images: [],
    imageIndex: 0,


    templates: [{
        thumb: 'https://6561-easyphoto-7gvh0dv16ef2d12c-1304274854.tcb.qcloud.la/setting/poster_template/1.svg?sign=7f211ea287fa7e15e239e93e860650be&t=1608387529',
        canvas: {
          width: parseInt(app.globalData.systemInfo.windowWidth),
          height: parseInt((app.globalData.systemInfo.windowHeight - app.globalData.systemInfo.windowWidth / 4))
        },
        imgwrap: {
          type: 'rect',
          width: parseInt(app.globalData.systemInfo.windowWidth),
          height: parseInt(app.globalData.systemInfo.windowHeight - app.globalData.systemInfo.windowWidth / 4 - app.globalData.systemInfo.windowWidth / 4),
          left: 0,
          top: 0,
        },
        studio: {
          title: {
            text: '轻萌摄影',
            left: parseInt(app.globalData.systemInfo.windowWidth * 0.3),
            top: parseInt(app.globalData.systemInfo.windowHeight - app.globalData.systemInfo.windowWidth / 4 - app.globalData.systemInfo.windowWidth / 4 + app.globalData.systemInfo.windowWidth / 4 * 0.25),
            fontsize: 18,
            color: "#000"
          },
          slogan: {
            text: '记录精彩瞬间',
            left: parseInt(app.globalData.systemInfo.windowWidth * 0.3),
            top: parseInt(app.globalData.systemInfo.windowHeight - app.globalData.systemInfo.windowWidth / 4 - app.globalData.systemInfo.windowWidth / 4 + app.globalData.systemInfo.windowWidth / 4 * 0.5),
            fontsize: 14,
            color: "#999"
          },
          qr: {
            path: 'https://6561-easyphoto-7gvh0dv16ef2d12c-1304274854.tcb.qcloud.la/qr.jpg?sign=619c86af3bcc1e6b0410299799f1b154&t=1606378223',
            left: parseInt(app.globalData.systemInfo.windowWidth / 4 * 0.2),
            top: parseInt(app.globalData.systemInfo.windowHeight - app.globalData.systemInfo.windowWidth / 4 - app.globalData.systemInfo.windowWidth / 4 + app.globalData.systemInfo.windowWidth / 4 * 0.1),
            width: parseInt(app.globalData.systemInfo.windowWidth / 4 * 0.8),
            height: parseInt(app.globalData.systemInfo.windowWidth / 4 * 0.8),
          },
        }
      },
      {
        thumb: 'https://6561-easyphoto-7gvh0dv16ef2d12c-1304274854.tcb.qcloud.la/setting/poster_template/2.svg?sign=9053a103b473f7e6f3dd955a362f2174&t=1608387745',
        canvas: {
          width: parseInt(app.globalData.systemInfo.windowWidth),
          height: parseInt((app.globalData.systemInfo.windowWidth + app.globalData.systemInfo.windowWidth / 4)),
        },
        imgwrap: {
          type: 'arc',
          width: parseInt(app.globalData.systemInfo.windowWidth * 0.9),
          height: parseInt(app.globalData.systemInfo.windowWidth * 0.9),
          left: parseInt(app.globalData.systemInfo.windowWidth * 0.05),
          top: parseInt(app.globalData.systemInfo.windowWidth * 0.05),
        },
        studio: {
          title: {
            text: '轻萌摄影',
            left: parseInt(app.globalData.systemInfo.windowWidth * 0.3),
            top: parseInt(app.globalData.systemInfo.windowWidth + app.globalData.systemInfo.windowWidth / 4 * 0.25),
            fontsize: 18,
            color: "#000"
          },
          slogan: {
            text: '记录精彩瞬间',
            left: parseInt(app.globalData.systemInfo.windowWidth * 0.3),
            top: parseInt(app.globalData.systemInfo.windowWidth + app.globalData.systemInfo.windowWidth / 4 * 0.5),
            fontsize: 14,
            color: "#999"
          },
          qr: {
            path: 'https://6561-easyphoto-7gvh0dv16ef2d12c-1304274854.tcb.qcloud.la/qr.jpg?sign=619c86af3bcc1e6b0410299799f1b154&t=1606378223',
            left: parseInt(app.globalData.systemInfo.windowWidth / 4 * 0.2),
            top: parseInt(app.globalData.systemInfo.windowWidth + app.globalData.systemInfo.windowWidth / 4 * 0.1),
            width: parseInt(app.globalData.systemInfo.windowWidth / 4 * 0.8),
            height: parseInt(app.globalData.systemInfo.windowWidth / 4 * 0.8),
          },
        }

      },

    ],
    posters: [

    ],

  },
  chooseImgs() {
    let images = this.data.images
    let imagesLength = images.length
    let that = this
    let templates = this.data.templates
    let currentTemplate = templates[0]
    let imgWrapWidth = currentTemplate.imgwrap.width
    let imgWrapHeight = currentTemplate.imgwrap.height

    wx.chooseImage({
      count: 9 - imagesLength,
      success(res) {
        console.log(res)
        let paths = res.tempFilePaths

        for (let i = 0; i < paths.length; i++) {
          wx.getImageInfo({
            src: paths[i],
            success(res1) {
              console.log(res1)
              //  let ratio = res1.width/res1.height
              let swidth = res1.width,
                sheight = res1.height,

                dwidth = sheight > swidth ? imgWrapWidth : swidth * imgWrapHeight / sheight,
                dheight = sheight > swidth ? sheight * imgWrapWidth / swidth : imgWrapHeight,
                scale = (sheight > swidth ? imgWrapWidth / swidth : imgWrapHeight / sheight).toFixed(1)

              let image = {
                path: res1.path,

                swidth: swidth,
                sheight: sheight,
                dwidth: dwidth,
                dheight: dheight,
                left: (imgWrapWidth - dwidth) / 2,
                top: (imgWrapHeight - dheight) / 2,
                scalemin: scale,
                scale: scale,
                templateIndex: 0
              }
              images.push(image)

              console.log(images)
              if (i == paths.length - 1) {
                that.setData({
                  images,
                  imageIndex: imagesLength
                })
              }
            }
          })

        }
      }
    })

  },

  changeTab(e) {
    let name = e.currentTarget.dataset.name
    this.setData({
      activeTab: name,
      showMenu:true
    })
  },
  changeTemplate(e) {
    let index = e.currentTarget.dataset.index
    let images = this.data.images
    let imageIndex = this.data.imageIndex
    let image = images[imageIndex]
    image.templateIndex = index
    //  image.imgWrapHeight

    this.setData({
      images
    })
  },
  changeImage(e) {
    let index = e.currentTarget.dataset.index
    this.setData({
      imageIndex: index
    })

  },
  removeImage(e) {
    let index = e.currentTarget.dataset.index
    let images = this.data.images
    images.splice(index, 1)
    this.setData({
      images
    })
  },
  onScale(e) {
    // console.log(e.detail)
    let images = this.data.images
    let imageIndex = this.data.imageIndex
    let image = images[imageIndex]
    let templates = this.data.templates
    let imgwrap = templates[image.templateIndex].imgwrap

    let scale = (e.detail.value).toFixed(1)
    console.log(scale)
    image.scale = scale
    image.dheight = image.sheight * scale
    image.dwidth = image.swidth * scale

    image.left = (imgwrap.width - image.dwidth) / 2
    image.top = (imgwrap.height - image.dheight) / 2

    console.log(images, templates[image.templateIndex])
    this.setData({
      images
    })
    console.log(images)
  },
  // onMove(e) {
  //   //  console.log(e.detail)
  //   let images = this.data.images
  //   let imageIndex = this.data.imageIndex
  //   let image = images[imageIndex]
  //   image.left = e.detail.x
  //   image.top = e.detail.y
  // },
  // 触摸开始事件处理函数
  touchstartCallback: function (e) {
    // this.getRect()
    let images = this.data.images
    let imageIndex = this.data.imageIndex
    let image = images[imageIndex]

    let {
      clientX,
      clientY
    } = e.touches[0]; // 结构获取 距离可视区域距离
    this.startX = clientX;
    this.startY = clientY;
    this.startLeft = image.left
    this.startTop = image.top
    this.touchStartEvent = e.touches
  },
  //触摸移动中
  touchmoveCallback: function (e) {
    let {
      clientX,
      clientY
    } = e.touches[0];
    let offsetX = clientX - this.startX;
    let offsetY = clientY - this.startY;
    this.offsetX = offsetX
    this.offsetY = offsetY
    //
    let images = this.data.images
    let imageIndex = this.data.imageIndex
    let image = images[imageIndex]

    image.left = this.startLeft + this.offsetX
    image.top = this.startTop + this.offsetY


    console.log(image.left, image.top)
    this.setData({
      images
    })

  },
  //触摸结束
  touchendCallback: function (e) {
    let images = this.data.images
    let imageIndex = this.data.imageIndex
    let image = images[imageIndex]
    let templates = this.data.templates
    let imgwrap = templates[image.templateIndex].imgwrap
    image.left = image.left + this.offsetX
    image.top = image.top + this.offsetY
    console.log(imgwrap)
    //左右
    if (image.dwidth >= imgwrap.width) {
      if (image.left >= 0) {
        image.left = 0
      }
      if (imgwrap.width - image.left >= image.dwidth) {
        image.left = imgwrap.width - image.dwidth
      }
    } else {
      if (image.left < 0) {
        image.left = 0
      }
      if (imgwrap.width - image.left < image.dwidth) {
        image.left = imgwrap.width - image.dwidth
      }
    }
    //上下
    if (image.dheight >= imgwrap.height) {
      if (image.top >= 0) {
        image.top = 0
      }
      if (imgwrap.height - image.top >= image.dheight) {
        image.top = imgwrap.height - image.dheight
      }
    } else {
      if (image.top < 0) {
        image.top = 0
      }
      if (imgwrap.height - image.top < image.dheight) {
        image.top = imgwrap.height - image.dheight
      }
    }
    console.log(image.left, image.top)
    this.setData({
      images
    })
    this.offsetX = 0
    this.offsetY = 0

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    if (!app.globalData.user.studio) return;

    let templates = this.data.templates
    for (let i = 0; i < templates.length; i++) {
      templates[i].studio.title.text = app.globalData.user.studio.title || ''
      templates[i].studio.slogan.text = app.globalData.user.studio.slogan || '长按识别二维码'
      templates[i].studio.qr.path = app.globalData.user.studio.qr || 'https://6561-easyphoto-7gvh0dv16ef2d12c-1304274854.tcb.qcloud.la/qr.jpg?sign=619c86af3bcc1e6b0410299799f1b154&t=1606378223'
    }
    this.setData({
      templates
    })

  },
  onShow() {

  },
  toggleMenu(){
    this.setData({
      showMenu:this.data.showMenu?false:true
    })
  },
  /*
   * getRect()	  获取节点信息，宽高，定位信息等
   * imageLoad() 获取当前图片的实际宽高
   */
  // 获取节点信息

  getTemplate(imageIndex) {
    let that = this
    let images = this.data.images
    let image = images[imageIndex]

    let templates = this.data.templates
    let templateIndex = image.templateIndex
    let template = templates[templateIndex]

    let canvas = template.canvas
    let imgwrap = template.imgwrap
    let studio = template.studio

    switch (templateIndex) {
      case 0:
        return {
          width: parseInt(canvas.width),
            height: parseInt(canvas.height),
            clear: true,
            views: [{
                type: 'rect',
                background: '#fff',
                top: 0,
                left: 0,
                width: parseInt(canvas.width),
                height: parseInt(canvas.height),
                //   radius: 10,
              },
              {
                type: 'image',
                url: image.path,
                top: image.top,
                left: image.left,
                width: image.dwidth,
                height: image.dheight,
                scale: image.scale,
                imgwrap: imgwrap

              },

              //  qr
              {
                type: 'image',
                url: studio.qr.path,
                top: studio.qr.top,
                left: studio.qr.left,
                width: studio.qr.width,
                height: studio.qr.height
              },
              //title
              {
                type: 'text',
                content: studio.title.text,
                fontSize: studio.title.fontsize,
                color: studio.title.color,
                textAlign: 'left',
                top: studio.title.top,
                left: studio.title.left,
                bolder: true
              },
              //slogan
              {
                type: 'text',
                content: studio.slogan.text,
                fontSize: studio.slogan.fontsize,
                color: studio.slogan.color,
                textAlign: 'left',
                top: studio.slogan.top,
                left: studio.slogan.left,
                bolder: false
              },
            ]
        };
        break;
      case 1:
        return {
          width: parseInt(canvas.width),
            height: parseInt(canvas.height),
            clear: true,
            views: [{
                type: 'rect',
                background: '#ffffff',
                top: 0,
                left: 0,
                width: parseInt(canvas.width),
                height: parseInt(canvas.height),
                //   radius: 10,
              },
              {
                type: 'image',
                url: image.path,
                top: image.top,
                left: image.left,
                width: image.dwidth,
                height: image.dheight,
                scale: image.scale,
                imgwrap: imgwrap

              },
              //  qr
              {
                type: 'image',
                url: studio.qr.path,
                top: studio.qr.top,
                left: studio.qr.left,
                width: studio.qr.width,
                height: studio.qr.height
              },
              //title
              {
                type: 'text',
                content: studio.title.text,
                fontSize: studio.title.fontsize,
                color: studio.title.color,
                textAlign: 'left',
                top: studio.title.top,
                left: studio.title.left,
                bolder: true
              },
              //slogan
              {
                type: 'text',
                content: studio.slogan.text,
                fontSize: studio.slogan.fontsize,
                color: studio.slogan.color,
                textAlign: 'left',
                top: studio.slogan.top,
                left: studio.slogan.left,
                bolder: false
              },
            ]

        };
        break;
    }

  },
  makeImg() {
    let images = this.data.images
    urls = []
    let poster = {}
    let posters = []
    wx.showLoading({
      title: '生成中...',
    })
    for (let i = 0; i < images.length; i++) {
      poster = this.getTemplate(i)
      posters.push(poster)
    }
    console.log(posters)
    this.setData({
      posters
    })

  },
  preview() {
    wx.previewImage({
      urls: urls,
      success: function () {

      },
      fail: function () {}
    })

  },
  saveImgs() {
    let url
    let that = this
    wx.getSetting({
      success: res => {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          //未授权的话发起授权
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success: () => {
              //用户允许授权，保存到相册

              for (url in urls) {
                that.saveImg(urls[url])
              }

            },
            fail: () => {
              //用户拒绝授权，然后就引导授权（这里的话如果用户拒绝，不会立马弹出引导授权界面，坑就是上边所说的官网原因）
              wx.showModal({
                content: '保存到相册需要获得你的授权',
                showCancel: false,
                confirmText: '确认',
                success: function (res) {
                  wx.openSetting({
                    success: () => {
                      wx.authorize({
                        scope: 'scope.writePhotosAlbum',
                        succes: () => {
                          //授权成功，保存图片
                          for (url in urls) {
                            that.saveImg(urls[url])
                          }
                        }
                      })
                    }
                  })
                },
                fail: function (res) {}
              })
            }
          })
        } else {
          //已经授权
          for (url in urls) {
            that.saveImg(urls[url])
          }
        }
      }
    })
  },
  saveImg(filePath) {
    var that = this
    wx.saveImageToPhotosAlbum({
      filePath: filePath,
      success(res) {
        wx.showToast({
          title: '保存成功',
          icon: 'none',
          duration: 2000
        })
      },
      fail: function (res) {
        wx.showToast({
          title: '保存失败',
          icon: 'none',
          duration: 2000
        })
      }
    })
  },

  eventGetImage(event) {
    const {
      tempFilePath,
      errMsg
    } = event.detail
    console.log('图片生成', event.detail)
    if (errMsg === 'canvasdrawer:ok') {
      urls.push(tempFilePath)
    }
    //  console.log(urls.length)
    if (urls.length == this.data.images.length) {
      wx.hideLoading()
      console.log(urls)
      this.setData({
        urls
      })
      this.preview()
    }
  }
});